package middleware

import (
	"blog-service/global"
	"blog-service/pkg/app"
	"blog-service/pkg/email"
	"blog-service/pkg/errcode"
	"fmt"
	"github.com/gin-gonic/gin"
	"time"
)

func Recovery() gin.HandlerFunc {
	defaultMailer := email.NewEmail(&email.SMTPInfo{
		Host:     global.EmailSettings.Host,
		Port:     global.EmailSettings.Port,
		IsSSL:    global.EmailSettings.IsSSL,
		UserName: global.EmailSettings.UserName,
		Password: global.EmailSettings.Password,
		From:     global.EmailSettings.From,
	})
	return func(context *gin.Context) {
		defer func() {
			if err := recover(); err != nil {
				global.Logger.WithCallersFrames().Errorf(context.Request.Context(), "panic recover err: %v", err)
				err := defaultMailer.SendMail(
					global.EmailSettings.To,
					fmt.Sprintf("异常抛出,发生时间: %d", time.Now().Unix()),
					fmt.Sprintf("错误信息: %v", err),
				)
				if err != nil {
					global.Logger.Panicf(context, ",mail.SendMail err: %v", err)
				}
				app.NewResponse(context).ToErrorResponse(errcode.ServerError)
				context.Abort()
			}
		}()
		context.Next()
	}
}
